<?php
namespace App\Models;

use CodeIgniter\Model;

class Admintor extends Model
{

    protected $table = 'admintor';

    protected $primaryKey = 'id';

    // 插入和更新数据自动更新created_at和updated_at
    protected $useTimestamps = true;

    // 插入和更新前，对密码进行加密
    protected $beforeInsert = [
        'beforeInsert'
    ];

    protected $beforeUpdate = [
        'beforeUpdate'
    ];

    // 默认是array，还可以是object
    // protected $returnType = 'array';
    // 使用软删除
    protected $useSoftDeletes = true;

    // save、insert或update方法期间设置的字段名更新此数组,除此之外的任何字段名都将被丢弃
    protected $allowedFields = [
        'username',
        'status',
        'password',
        'mobile',
        'realname',
        'desc',
        'created_at',
        'updated_at'
    ];

    protected $validationRules = [
        'username' => [
            'label' => '用户名',
            'rules' => 'required'
        ],
        'password' => [
            'label' => '密码',
            'rules' => 'required|min_length[6]|max_length[32]'
        ],
        'realname' => [
            'label' => '真实名字',
            'rules' => 'required|valid_realname'
        ],
        'mobile' => [
            'label' => '手机号',
            'rules' => 'required|valid_mobile'
        ],
        'desc' => [
            'label' => '备注',
            'rules' => 'max_length[256]'
        ],
        'status' => [
            'label' => '状态',
            'rules' => 'required|in_list[' . COMMON_STATUS_ON . ',' . COMMON_STATUS_OFF . ']',
            'errors' => [
                'in_list' => '状态值必须是启用或禁用'
            ]
        ]
    ];

    // protected $skipValidation = false;
    
    // 插入前事件
    protected function beforeInsert(array $data)
    {
        $data = $this->passwordHash($data);
        $data['data']['created_at'] = date('Y-m-d H:i:s');
        return $data;
    }

    // 更新前事件
    protected function beforeUpdate(array $data)
    {
        $data = $this->passwordHash($data);
        $data['data']['updated_at'] = date('Y-m-d H:i:s');
        return $data;
    }

    // 加密密码
    protected function passwordHash(array $data)
    {
        if (isset($data['data']['password']))
            $data['data']['password_hash'] = password_hash(sha1(md5($data['data']['password'])), PASSWORD_DEFAULT);
        unset($data['data']['password']);
        return $data;
    }

    /**
     * 设置登录session
     */
    public function setSession($admintor)
    {
        $data = [
            'id' => $admintor['id'],
            'username' => $admintor['username'],
            'is_super' => intval($admintor['is_super']),
            'status' => intval($admintor['status']),
            'mobile' => $admintor['mobile'],
            'realname' => $admintor['realname'],
            'desc' => $admintor['desc'],
            'isLoggedIn' => true
        ];
        session()->set($data);
        return true;
    }
}